<template>
  <AppLayout title="忘记密码" :show-back="true">
    <view class="forgot-password-container">
      <!-- 头部说明 -->
      <view class="header-section">
        <view class="header-icon">🔐</view>
        <text class="header-title">找回密码</text>
        <text class="header-desc">请输入您的账号信息，我们将发送验证码到您的邮箱</text>
      </view>

      <!-- 步骤指示器 -->
      <view class="steps-container">
        <view class="steps">
          <view
            v-for="(step, index) in steps"
            :key="index"
            class="step-item"
            :class="{ 'step-item--active': currentStep === index, 'step-item--completed': currentStep > index }"
          >
            <view class="step-number">{{ currentStep > index ? '✓' : index + 1 }}</view>
            <text class="step-text">{{ step }}</text>
            <view v-if="index < steps.length - 1" class="step-line"></view>
          </view>
        </view>
      </view>

      <!-- 表单内容 -->
      <view class="form-section">
        <!-- 步骤1: 验证身份 -->
        <view v-if="currentStep === 0" class="step-content">
          <FormInput
            v-model="formData.username"
            label="用户名"
            placeholder="请输入用户名"
            prefix-icon="👤"
            required
            :error="errors.username"
            @blur="validateUsername"
          />

          <FormInput
            v-model="formData.email"
            label="邮箱地址"
            type="text"
            placeholder="请输入注册时使用的邮箱"
            prefix-icon="📧"
            required
            :error="errors.email"
            @blur="validateEmail"
          />

          <FormInput
            v-model="formData.captcha"
            label="验证码"
            placeholder="请输入验证码"
            prefix-icon="🔢"
            required
            :error="errors.captcha"
          >
            <template #suffix>
              <image class="captcha-image" :src="captchaUrl" @click="refreshCaptcha" />
            </template>
          </FormInput>
        </view>

        <!-- 步骤2: 验证邮箱验证码 -->
        <view v-if="currentStep === 1" class="step-content">
          <view class="verification-info">
            <text class="info-text">验证码已发送至您的邮箱</text>
            <text class="email-text">{{ formData.email }}</text>
          </view>

          <FormInput
            v-model="formData.emailCode"
            label="邮箱验证码"
            placeholder="请输入6位验证码"
            prefix-icon="✉️"
            required
            :error="errors.emailCode"
            maxlength="6"
          >
            <template #suffix>
              <FormButton
                :text="resendText"
                :disabled="resendCountdown > 0"
                type="text"
                size="small"
                @click="sendEmailCode"
              />
            </template>
          </FormInput>
        </view>

        <!-- 步骤3: 设置新密码 -->
        <view v-if="currentStep === 2" class="step-content">
          <FormInput
            v-model="formData.newPassword"
            label="新密码"
            type="password"
            placeholder="请输入新密码"
            prefix-icon="🔑"
            required
            :error="errors.newPassword"
            show-password-toggle
            @blur="validateNewPassword"
          />

          <!-- 密码强度指示器 -->
          <view v-if="formData.newPassword" class="password-strength">
            <text class="strength-label">密码强度</text>
            <view class="strength-bar">
              <view
                v-for="level in 4"
                :key="level"
                class="strength-item"
                :class="getStrengthClass(level)"
              ></view>
            </view>
            <text class="strength-text">{{ strengthText }}</text>
          </view>

          <FormInput
            v-model="formData.confirmPassword"
            label="确认新密码"
            type="password"
            placeholder="请再次输入新密码"
            prefix-icon="🔑"
            required
            :error="errors.confirmPassword"
            show-password-toggle
            @blur="validateConfirmPassword"
          />

          <!-- 密码要求 -->
          <view class="password-requirements">
            <text class="requirements-title">密码要求：</text>
            <view class="requirement-item" :class="{ 'requirement-met': meetsLength }">
              <text class="requirement-icon">{{ meetsLength ? '✓' : '○' }}</text>
              <text class="requirement-text">至少6个字符</text>
            </view>
            <view class="requirement-item" :class="{ 'requirement-met': hasLetter }">
              <text class="requirement-icon">{{ hasLetter ? '✓' : '○' }}</text>
              <text class="requirement-text">包含字母</text>
            </view>
            <view class="requirement-item" :class="{ 'requirement-met': hasNumber }">
              <text class="requirement-icon">{{ hasNumber ? '✓' : '○' }}</text>
              <text class="requirement-text">包含数字</text>
            </view>
            <view class="requirement-item" :class="{ 'requirement-met': hasSpecial }">
              <text class="requirement-icon">{{ hasSpecial ? '✓' : '○' }}</text>
              <text class="requirement-text">包含特殊字符（可选）</text>
            </view>
          </view>
        </view>

        <!-- 步骤4: 完成重置 -->
        <view v-if="currentStep === 3" class="step-content">
          <view class="success-content">
            <view class="success-icon">🎉</view>
            <text class="success-title">密码重置成功</text>
            <text class="success-desc">您的密码已成功重置，请使用新密码登录</text>
          </view>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="action-section">
        <!-- 上一步按钮 -->
        <FormButton
          v-if="currentStep > 0 && currentStep < 3"
          text="上一步"
          type="secondary"
          size="large"
          block
          @click="prevStep"
        />

        <!-- 下一步/提交按钮 -->
        <FormButton
          v-if="currentStep < 3"
          :text="currentStep === 2 ? '重置密码' : '下一步'"
          type="primary"
          size="large"
          :loading="loading"
          :disabled="!canProceed"
          block
          @click="nextStep"
        />

        <!-- 返回登录按钮 -->
        <FormButton
          v-if="currentStep === 3"
          text="返回登录"
          type="primary"
          size="large"
          block
          @click="goToLogin"
        />
      </view>

      <!-- 全屏加载 -->
      <AppLoading
        v-if="globalLoading"
        type="fullscreen"
        :text="loadingText"
      />
    </view>
  </AppLayout>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { navigation } from '@/utils/navigation'
import AppLayout from '@/components/common/AppLayout.vue'
import FormInput from '@/components/common/FormInput.vue'
import FormButton from '@/components/common/FormButton.vue'
import AppLoading from '@/components/common/AppLoading.vue'

// 响应式数据
const currentStep = ref(0)
const loading = ref(false)
const globalLoading = ref(false)
const loadingText = ref('处理中...')
const resendCountdown = ref(0)
const captchaUrl = ref('https://via.placeholder.com/100x40/CCCCCC/FFFFFF?text=CAPTCHA')

// 步骤定义
const steps = ['验证身份', '邮箱验证', '设置密码', '完成重置']

// 表单数据
const formData = reactive({
  username: '',
  email: '',
  captcha: '',
  emailCode: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证错误
const errors = reactive({
  username: '',
  email: '',
  captcha: '',
  emailCode: '',
  newPassword: '',
  confirmPassword: ''
})

// 计算属性
const canProceed = computed(() => {
  switch (currentStep.value) {
    case 0:
      return formData.username.trim() !== '' &&
             formData.email.trim() !== '' &&
             formData.captcha.trim() !== '' &&
             Object.values(errors).slice(0, 3).every(error => error === '')
    case 1:
      return formData.emailCode.trim() !== '' && !errors.emailCode
    case 2:
      return formData.newPassword.trim() !== '' &&
             formData.confirmPassword.trim() !== '' &&
             formData.newPassword === formData.confirmPassword &&
             meetsLength.value && hasLetter.value && hasNumber.value &&
             Object.values(errors).slice(4).every(error => error === '')
    default:
      return false
  }
})

const passwordStrength = computed(() => {
  const password = formData.newPassword
  let strength = 0

  if (password.length >= 6) strength++
  if (password.length >= 8) strength++
  if (/[a-z]/.test(password) && /[A-Z]/.test(password)) strength++
  if (/\d/.test(password)) strength++
  if (/[^a-zA-Z0-9]/.test(password)) strength++

  return strength
})

const strengthText = computed(() => {
  const strength = passwordStrength.value
  if (strength === 0) return '很弱'
  if (strength === 1) return '弱'
  if (strength === 2) return '一般'
  if (strength === 3) return '强'
  if (strength === 4) return '很强'
  return '很弱'
})

const meetsLength = computed(() => formData.newPassword.length >= 6)
const hasLetter = computed(() => /[a-zA-Z]/.test(formData.newPassword))
const hasNumber = computed(() => /\d/.test(formData.newPassword))
const hasSpecial = computed(() => /[^a-zA-Z0-9]/.test(formData.newPassword))

const resendText = computed(() => {
  return resendCountdown.value > 0 ? `${resendCountdown.value}s后重试` : '重新发送'
})

// 方法
/**
 * 验证用户名
 */
const validateUsername = () => {
  errors.username = ''

  if (!formData.username.trim()) {
    errors.username = '请输入用户名'
  } else if (formData.username.length < 3) {
    errors.username = '用户名至少3个字符'
  } else if (!/^[a-zA-Z0-9_]+$/.test(formData.username)) {
    errors.username = '用户名只能包含字母、数字和下划线'
  }
}

/**
 * 验证邮箱
 */
const validateEmail = () => {
  errors.email = ''

  if (!formData.email.trim()) {
    errors.email = '请输入邮箱地址'
  } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
    errors.email = '请输入有效的邮箱地址'
  }
}

/**
 * 验证新密码
 */
const validateNewPassword = () => {
  errors.newPassword = ''

  if (!formData.newPassword.trim()) {
    errors.newPassword = '请输入新密码'
  } else if (formData.newPassword.length < 6) {
    errors.newPassword = '密码至少6个字符'
  } else if (!hasLetter.value || !hasNumber.value) {
    errors.newPassword = '密码必须包含字母和数字'
  }
}

/**
 * 验证确认密码
 */
const validateConfirmPassword = () => {
  errors.confirmPassword = ''

  if (!formData.confirmPassword.trim()) {
    errors.confirmPassword = '请确认新密码'
  } else if (formData.newPassword !== formData.confirmPassword) {
    errors.confirmPassword = '两次输入的密码不一致'
  }
}

/**
 * 获取密码强度样式类
 */
const getStrengthClass = (level: number) => {
  const strength = passwordStrength.value
  if (strength >= level) {
    const classes = ['weak', 'fair', 'good', 'strong']
    return `strength-${classes[level - 1]}`
  }
  return ''
}

/**
 * 刷新验证码
 */
const refreshCaptcha = () => {
  captchaUrl.value = `https://via.placeholder.com/100x40/CCCCCC/FFFFFF?text=${Math.random().toString(36).substr(2, 6).toUpperCase()}`
}

/**
 * 发送邮箱验证码
 */
const sendEmailCode = async () => {
  if (resendCountdown.value > 0) return

  try {
    loading.value = true

    // 模拟发送验证码
    await new Promise(resolve => setTimeout(resolve, 1000))

    uni.showToast({
      title: '验证码已发送',
      icon: 'success'
    })

    // 开始倒计时
    resendCountdown.value = 60
    const timer = setInterval(() => {
      resendCountdown.value--
      if (resendCountdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)

  } catch (error) {
    console.error('发送验证码失败:', error)
    uni.showToast({
      title: '发送失败，请重试',
      icon: 'error'
    })
  } finally {
    loading.value = false
  }
}

/**
 * 下一步
 */
const nextStep = async () => {
  // 验证当前步骤
  let isValid = true

  switch (currentStep.value) {
    case 0:
      validateUsername()
      validateEmail()
      if (errors.username || errors.email || !formData.captcha.trim()) {
        isValid = false
        if (!formData.captcha.trim()) {
          errors.captcha = '请输入验证码'
        }
      }
      break
    case 1:
      if (!formData.emailCode.trim() || formData.emailCode.length !== 6) {
        errors.emailCode = '请输入6位验证码'
        isValid = false
      }
      break
    case 2:
      validateNewPassword()
      validateConfirmPassword()
      if (errors.newPassword || errors.confirmPassword) {
        isValid = false
      }
      break
  }

  if (!isValid) return

  try {
    loading.value = true
    globalLoading.value = true

    // 模拟API调用
    switch (currentStep.value) {
      case 0:
        loadingText.value = '验证身份中...'
        await new Promise(resolve => setTimeout(resolve, 1500))
        break
      case 1:
        loadingText.value = '验证邮箱中...'
        await new Promise(resolve => setTimeout(resolve, 1500))
        break
      case 2:
        loadingText.value = '重置密码中...'
        await new Promise(resolve => setTimeout(resolve, 2000))
        break
    }

    currentStep.value++

  } catch (error) {
    console.error('操作失败:', error)
    uni.showToast({
      title: '操作失败，请重试',
      icon: 'error'
    })
  } finally {
    loading.value = false
    globalLoading.value = false
    loadingText.value = '处理中...'
  }
}

/**
 * 上一步
 */
const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

/**
 * 返回登录
 */
const goToLogin = () => {
  navigation.toLogin()
}
</script>

<style lang="scss" scoped>
.forgot-password-container {
  min-height: 100vh;
  background: #f8f9fa;
  padding: 20px;
}

.header-section {
  text-align: center;
  margin-bottom: 32px;

  .header-icon {
    font-size: 48px;
    margin-bottom: 16px;
  }

  .header-title {
    display: block;
    font-size: 24px;
    font-weight: 600;
    color: #333;
    margin-bottom: 8px;
  }

  .header-desc {
    display: block;
    font-size: 14px;
    color: #666;
    line-height: 1.5;
  }
}

.steps-container {
  margin-bottom: 32px;

  .steps {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
  }

  .step-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    flex: 1;

    .step-number {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      background: #f0f0f0;
      color: #999;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 14px;
      font-weight: 600;
      margin-bottom: 8px;
      transition: all 0.3s ease;
    }

    .step-text {
      font-size: 12px;
      color: #999;
      text-align: center;
      line-height: 1.2;
    }

    .step-line {
      position: absolute;
      top: 16px;
      left: 50%;
      width: 100%;
      height: 2px;
      background: #f0f0f0;
      z-index: 1;
    }

    &--active {
      .step-number {
        background: #1890ff;
        color: #fff;
      }

      .step-text {
        color: #1890ff;
      }
    }

    &--completed {
      .step-number {
        background: #52c41a;
        color: #fff;
      }

      .step-text {
        color: #52c41a;
      }

      .step-line {
        background: #52c41a;
      }
    }

    &:last-child {
      .step-line {
        display: none;
      }
    }
  }
}

.form-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
}

.step-content {
  min-height: 200px;
}

.verification-info {
  text-align: center;
  padding: 24px;
  background: #f0f9ff;
  border-radius: 8px;
  margin-bottom: 24px;

  .info-text {
    display: block;
    font-size: 14px;
    color: #1890ff;
    margin-bottom: 8px;
  }

  .email-text {
    display: block;
    font-size: 16px;
    font-weight: 600;
    color: #333;
  }
}

.password-strength {
  margin: 16px 0;

  .strength-label {
    display: block;
    font-size: 14px;
    font-weight: 500;
    color: #666;
    margin-bottom: 8px;
  }

  .strength-bar {
    display: flex;
    gap: 4px;
    margin-bottom: 8px;

    .strength-item {
      flex: 1;
      height: 6px;
      background: #f0f0f0;
      border-radius: 3px;
      transition: all 0.3s ease;

      &.strength-weak {
        background: #ff4757;
      }

      &.strength-fair {
        background: #ffa502;
      }

      &.strength-good {
        background: #ffdd59;
      }

      &.strength-strong {
        background: #5cb85c;
      }
    }
  }

  .strength-text {
    font-size: 12px;
    color: #666;
    font-weight: 500;
  }
}

.password-requirements {
  margin-top: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;

  .requirements-title {
    display: block;
    font-size: 14px;
    font-weight: 600;
    color: #333;
    margin-bottom: 12px;
  }

  .requirement-item {
    display: flex;
    align-items: center;
    margin-bottom: 8px;

    &:last-child {
      margin-bottom: 0;
    }

    &.requirement-met {
      .requirement-icon {
        color: #5cb85c;
      }

      .requirement-text {
        color: #5cb85c;
      }
    }

    .requirement-icon {
      font-size: 16px;
      margin-right: 8px;
      color: #ddd;
      width: 16px;
      text-align: center;
    }

    .requirement-text {
      font-size: 13px;
      color: #666;
    }
  }
}

.success-content {
  text-align: center;
  padding: 40px 20px;

  .success-icon {
    font-size: 64px;
    margin-bottom: 24px;
  }

  .success-title {
    display: block;
    font-size: 20px;
    font-weight: 600;
    color: #333;
    margin-bottom: 12px;
  }

  .success-desc {
    display: block;
    font-size: 14px;
    color: #666;
    line-height: 1.5;
  }
}

.action-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.captcha-image {
  width: 100px;
  height: 40px;
  border-radius: 4px;
  cursor: pointer;
}

// 响应式设计
@media (max-width: 480px) {
  .forgot-password-container {
    padding: 16px;
  }

  .form-section {
    padding: 20px 16px;
  }

  .steps-container {
    .steps {
      padding: 0 10px;
    }

    .step-item {
      .step-number {
        width: 28px;
        height: 28px;
        font-size: 12px;
      }

      .step-text {
        font-size: 11px;
      }
    }
  }
}

// 动画
.form-section {
  animation: slideUp 0.6s cubic-bezier(0.4, 0, 0.2, 1);
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>